//
//  MKAnalytics.m
//  MKAnalytics
//
//  Created by zhuwh on 2017/1/18.
//  Copyright © 2017年 mark. All rights reserved.
//

#import "MAKAnalytics.h"
#import "Aspects/Aspects.h"
#import "UMMobClick/MobClick.h"

@implementation MAKAnalyticsConfig

SingletonM(Instance);

@end
@implementation MAKAnalytics

+(void)initialize{
    if (self == [MAKAnalytics self]) {
//        NSLog(@"%s",__func__);
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [UIViewController aspect_hookSelector:@selector(viewWillAppear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo, BOOL animated) {
                UIViewController *controller = aspectInfo.instance;
                [weakSelf beginLogPageView:[controller class]];
            } error:NULL];
            
            [UIViewController aspect_hookSelector:@selector(viewWillDisappear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo, BOOL animated) {
                UIViewController *controller = aspectInfo.instance;
                [weakSelf endLogPageView:[controller class]];
            } error:NULL];
            
        });
    }
}

+ (void)beginLogPageView:(__unsafe_unretained Class)pageView {
    [self beginLogPageViewName:NSStringFromClass(pageView)];
}

+ (void)endLogPageView:(__unsafe_unretained Class)pageView {
    [self endLogPageViewName:NSStringFromClass(pageView)];
}

+(void)beginLogPageViewName:(NSString *)pageViewName
{
    if([MAKAnalyticsConfigInstance.ignoreList containsObject:pageViewName]){
        return; //在忽略列表的中表不做统计
    }
    [MobClick beginLogPageView:pageViewName];
}

+(void)endLogPageViewName:(NSString *)pageViewName
{
    if([MAKAnalyticsConfigInstance.ignoreList containsObject:pageViewName]){
        return; //在忽略列表的中表不做统计
    }
    [MobClick endLogPageView:pageViewName];
}

+(void)logEvent:(NSString*)eventId
{
    [MobClick event:eventId];
}

+(void)logEvent:(NSString*)eventId attributes:(NSDictionary *)attributes
{
    [MobClick event:eventId attributes:attributes];
}

+ (void) startWithConfigure:(MAKAnalyticsConfig*)configure{
    UMConfigInstance.appKey=MAKAnalyticsConfigInstance.appKey;
    
    if (MAKAnalyticsConfigInstance.channelId) {
        UMConfigInstance.channelId=MAKAnalyticsConfigInstance.channelId;
    }

    if (MAKAnalyticsConfigInstance.bCrashReportEnabled) {
        UMConfigInstance.bCrashReportEnabled=YES;
    }
    [MobClick startWithConfigure:UMConfigInstance];
    // version标识
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    
}

+(void) setLogEnabled:(BOOL)enabled{
    [MobClick setLogEnabled:enabled];
}

@end
